package com.antSort;

import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

public class demoControl {

    @FXML
    ComboBox<String> methodSelect;
    @FXML
    Button browse;
    @FXML
    Button operate;
    @FXML
    Label operationTime;
    @FXML
    Label operationResult;
    @FXML
    private ImageView RecImageView;
    @FXML
    private TextField filePathTextField;
    @FXML
    public void initialize() {
        // 创建一个包含初始选项的列表
        List<String> options = Arrays.asList("cplex直接求解", "cplex定价求解","蚁群求解");
        // 将选项添加到 ComboBox
        methodSelect.setItems(FXCollections.observableArrayList(options));
        methodSelect1.setItems(FXCollections.observableArrayList(options));
    }

    public void onBrowse(){
        FileChooser chooser=new FileChooser();
        chooser.setInitialDirectory(new File("E:/java/AllCODE/postgraduateCultivate/cultivateOne/instance"));
        //设置初始路径
        chooser.setTitle("打开文件");
        File selectedFile = chooser.showOpenDialog(null);
        if (selectedFile!= null) {
            // 将文件路径设置到 TextField
            filePathTextField.setText(selectedFile.getAbsolutePath());
        }else {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("提示");
            alert.setHeaderText(null);
            alert.setContentText("未选择文件或者操作被取消。");
            // 显示对话框
            alert.showAndWait();
        }
    }

    public void onOperate() throws Exception {
        String filePath = filePathTextField.getText();
        String method=methodSelect.getValue();
        if (filePath!= null &&!filePath.isEmpty()) {
            switch (method){
                case "请选择一个求解方式":
                    Alert alert = new Alert(Alert.AlertType.WARNING);
                    alert.setTitle("警告");
                    alert.setHeaderText(null);
                    alert.setContentText("请选择一个求解方式。");
                    alert.showAndWait();
                    break;
                case "cplex直接求解":
                    data data=new data();
                    data.readFile(filePath,1);
                    cplex model = new cplex(data);
                    model.runModel(1);
                    double seconds = model.getRunTime()/ 1000.0;
                    operationResult.setText(String.valueOf(model.cost));
                    operationTime.setText(seconds+"s");
                    ArrayList<int[]> list =model.getLocationAndSize();
                    drawRectangle(list,5);
                    break;
                case "cplex定价求解":
                    Alert alert0 = new Alert(Alert.AlertType.WARNING);
                    alert0.setHeaderText(null);
                    alert0.setContentText("见新代码");
                    alert0.showAndWait();
                    break;
                case "蚁群求解":
                    antData.readFile("instance/cgcut1.txt");
//                    antData.judge();
                    antNode root = new antNode(0, 0, new int[]{0, 0}, new int[]{antData.getL()[0], antData.getL()[1]});
                    int antNum = 20;
                    for (int loop = 0; loop < 100; loop++) {
                        ArrayList<antPath> antPaths = new ArrayList<>();
                        for (int i = 0; i < antNum; i++) {
                            try {
                                antPath path1 = new antPath(root);
                                if (path1.pathJudge()) {
                                    antPaths.add(path1);
                                } else i--;
                            } catch (Exception e) {
                                // 处理创建 antPath 对象时的异常
                                System.err.println("创建蚂蚁路径对象失败：" + e.getMessage());
                            }
                        }
                        int[] maxValueAndIndex = new int[]{0, 0};

                        for (int i = 0; i < antPaths.size(); i++) {
                            if (antPaths.get(i).getPathValue() > maxValueAndIndex[0]) {
                                maxValueAndIndex[0] = antPaths.get(i).getPathValue();
                                maxValueAndIndex[1] = i;
                            }
                        }
                        antPath.updatePheromone(antPaths.get(maxValueAndIndex[1]).getResult());
                        if (maxValueAndIndex[0] > 0) {
                            System.out.println("最优解及其对应path索引为：" + maxValueAndIndex[0] + "," + maxValueAndIndex[1]);
                        }
                    }
                    drawRectangleOfAnt();
                    break;
            }
        } else {
            // 如果 filePathTextField 中没有有效的文件路径，则弹出提示
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setTitle("警告");
            alert.setHeaderText(null);
            alert.setContentText("请先选择有效的文件路径。");
            alert.showAndWait();
        }
    }

    public void drawRectangleOfAnt() {

    }
    public void drawRectangle(ArrayList<int[]> list ,int multiple) {
        // 获取 ImageView 的实际宽度和高度
        double imageViewWidth = RecImageView.getFitWidth();
        double imageViewHeight = RecImageView.getFitHeight();

        Canvas canvas = new Canvas(imageViewWidth, imageViewHeight);
        GraphicsContext gc = canvas.getGraphicsContext2D();
        gc.setFill(Color.WHITE); // 设置画布背景为白色（可选，根据需要）
        ArrayList<Color> colors = new ArrayList<>(Arrays.asList(Color.RED, Color.BLUE, Color.GREEN, Color.ORANGE, Color.PINK, Color.GRAY, Color.YELLOW, Color.CYAN));
        gc.fillRect(0, 0, imageViewWidth, imageViewHeight);
        Random random = new Random();
        for (int[] recNum : list) {
            double x = recNum[0]*multiple;
            double y = imageViewHeight - multiple*(recNum[3] + recNum[1]);
            double l = recNum[2]*multiple;
            double w = recNum[3]*multiple;

            Color color = colors.get(random.nextInt(colors.size()));
            gc.setFill(color);

            gc.fillRect(x, y, l, w);
            gc.strokeRect(x, y, l, w);
            gc.fillRect(x, y, l, w);
        }
        RecImageView.setImage(canvas.snapshot(null, null));
        System.out.println("打印完成");
    }
    @FXML
    Button browse1;
    @FXML
    ComboBox<String> methodSelect1;
    @FXML
    TextArea filePathTextField1;
    @FXML
    Button operate1;
    @FXML
    GridPane gridPane;
    private  List<String> fileNames;
    public void onBrowse1(){
        DirectoryChooser chooser = new DirectoryChooser();
        chooser.setInitialDirectory(new File("E:/java/AllCODE/postgraduateCultivate"));
        chooser.setTitle("选择文件夹");
        File selectedDirectory = chooser.showDialog(null);
        if (selectedDirectory!= null) {
            File[] files = selectedDirectory.listFiles();
            if (files!= null) {
                fileNames = Arrays.stream(files)
                        .map(File::getName)
                        .toList();
                filePathTextField1.clear();
                for (String fileName : fileNames) {
                    filePathTextField1.appendText(fileName + "\n");
                }
            }
        } else {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("提示");
            alert.setHeaderText(null);
            alert.setContentText("未选择文件夹或者操作被取消。");
            alert.showAndWait();
        }
    }
    public void onOperate1() throws Exception {
        String filePath = "E:/java/AllCODE/postgraduateCultivate/cultivateOne/instance";
        String method=methodSelect1.getValue();
        if (fileNames!= null &&!fileNames.isEmpty()) {
            switch (method){
                case "请选择一个求解方式":
                    Alert alert = new Alert(Alert.AlertType.WARNING);
                    alert.setTitle("警告");
                    alert.setHeaderText(null);
                    alert.setContentText("请选择一个求解方式。");
                    alert.showAndWait();
                    break;
                case "cplex直接求解":
                    String[] value=new String[fileNames.size()];
                    String[] seconds=new String[fileNames.size()];
                    for (int i = 0; i < fileNames.size(); i++) {
                        String fileName=fileNames.get(i);
                        String filePathTmp= filePath + "/" + fileName;
                        data data=new data();
                        data.readFile(filePathTmp,1);
                        cplex model = new cplex(data);
                        model.runModel(1);
                        double second = model.getRunTime()/ 1000.0;
                        value[i]=String.valueOf(model.cost);
                        seconds[i]=second+"s";
                    }
                    for (int i = 0; i < fileNames.size(); i++) {
                        // 创建用于展示 filepath 的 Label
                        Label filePathLabel = new Label(fileNames.get(i));
                        // 创建用于展示 value 的 Label
                        Label valueLabel = new Label(value[i]);
                        // 创建用于展示 seconds 的 Label
                        Label secondsLabel = new Label(seconds[i]);
                        // 将三个 Label 添加到 GridPane 的对应位置，从第一行开始每行放置
                        gridPane.add(filePathLabel, 0, i, 1, 1);
                        gridPane.add(valueLabel, 1, i, 1, 1);
                        gridPane.add(secondsLabel, 2, i, 1, 1);
                    }
                    for (int i = 0; i < fileNames.size(); i++) {
                        System.out.println(fileNames.get(i)+"价值为"+value[i]+";运行时间为"+seconds[i]);
                    }
                    break;
            }
        } else {
            // 如果 filePathTextField 中没有有效的文件路径，则弹出提示
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setTitle("警告");
            alert.setHeaderText(null);
            alert.setContentText("请先选择有效的文件路径。");
            alert.showAndWait();
        }
    }
}
